﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace _404park.Utilities.Extensions
{
    public static class XElementExtensions
    {
        public static string ReadInnerTags(this XElement parent)
        {
            var attributes = GetAttributes(parent);
            var defaultNameSpace = GetDefaultNameSpace(parent);

            var openningTag = string.Format("<{0}", parent.Name.LocalName);
            openningTag += !string.IsNullOrEmpty(attributes) ? string.Format(" {0}", attributes) : string.Empty;
            openningTag += !string.IsNullOrEmpty(defaultNameSpace) ? string.Format(" {0}", defaultNameSpace) : string.Empty;
            openningTag += ">";

            var enddingTag = string.Format("</{0}>", parent.Name.LocalName);

            return StringExtensions.HtmlDecode(parent.ToString()).Replace(openningTag, string.Empty).Replace(enddingTag, string.Empty);
        }

        private static string GetAttributes(XElement element)
        {
            if (!element.HasAttributes)
                return string.Empty;

            var value = string.Empty;

            foreach (var attribute in element.Attributes())
            {
                value += string.Format("{0}=\"{1}\"", attribute.Name, attribute.Value) + " ";
            }

            return value.Trim();
        }

        private static string GetDefaultNameSpace(XElement element)
        {
            if (string.IsNullOrEmpty(element.Name.NamespaceName))
                return string.Empty;

            return string.Format("xmlns=\"{0}\"", element.Name.NamespaceName);
        }
    }
}
